package com.uyayo.framework.common.util.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.uyayo.framework.common.exception.FileException;

public class FileUtil {

	public static String PATH_SEPARATOR = File.separator;

	public static String DEFAULT_FILE_EXTENSION = ".tmp";

	public static DateFormat DATEFORMAT_TIME17BIT = new SimpleDateFormat(
	    "yyyyMMddHHmmssSSS");
	public static final int BUFFER_SIZE = 4096;

	public static void main(String[] args) {
		String dirName = "d:/Best/topic/";// 创建目录
		FileUtil.createDir(dirName);
	}

	/**
	 * 创建目录
	 * 
	 * @param destDirName
	 *            目标目录名
	 * @return 目录创建成功返回true，否则返回false
	 */
	public static boolean createDir(String destDirName) {
		File dir = new File(destDirName);
		if (dir.exists()) {
			return false;
		}
		if (!destDirName.endsWith(File.separator)) {
			destDirName = destDirName + File.separator;
		}
		// 创建单个目录
		if (dir.mkdirs()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 删除文件
	 * 
	 * @param filePathAndName
	 *            String 文件路径及名称 如c:/fqf.txt
	 * @param fileContent
	 *            String
	 * @return boolean
	 */
	public static void delFile(String filePathAndName) {
		try {
			String filePath = filePathAndName;
			filePath = filePath.toString();
			java.io.File myDelFile = new java.io.File(filePath);
			myDelFile.delete();

		} catch (Exception e) {
			System.out.println("删除文件操作出错");
			e.printStackTrace();

		}

	}

	/**
	 * 读取到字节数组0
	 * 
	 * @param filePath //路径
	 * @throws IOException
	 */
	public static byte[] getContent(String filePath) throws IOException {
		File file = new File(filePath);
		long fileSize = file.length();
		if (fileSize > Integer.MAX_VALUE) {
			System.out.println("file too big...");
			return null;
		}
		FileInputStream fi = new FileInputStream(file);
		byte[] buffer = new byte[(int) fileSize];
		int offset = 0;
		int numRead = 0;
		while (offset < buffer.length
				&& (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
			offset += numRead;
		}
		// 确保所有数据均被读取
		if (offset != buffer.length) {
			throw new IOException("Could not completely read file "
					+ file.getName());
		}
		fi.close();
		return buffer;
	}

	/**
	 * 读取到字节数组1
	 * 
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	public static byte[] toByteArray(String filePath) throws IOException {

		File f = new File(filePath);
		if (!f.exists()) {
			throw new FileNotFoundException(filePath);
		}
		ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
		BufferedInputStream in = null;
		try {
			in = new BufferedInputStream(new FileInputStream(f));
			int buf_size = 1024;
			byte[] buffer = new byte[buf_size];
			int len = 0;
			while (-1 != (len = in.read(buffer, 0, buf_size))) {
				bos.write(buffer, 0, len);
			}
			return bos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			bos.close();
		}
	}

	/**
	 * 读取到字节数组2
	 * 
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	public static byte[] toByteArray2(String filePath) throws IOException {

		File f = new File(filePath);
		if (!f.exists()) {
			throw new FileNotFoundException(filePath);
		}

		FileChannel channel = null;
		FileInputStream fs = null;
		try {
			fs = new FileInputStream(f);
			channel = fs.getChannel();
			ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
			while ((channel.read(byteBuffer)) > 0) {
				// do nothing
				// System.out.println("reading");
			}
			return byteBuffer.array();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				channel.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				fs.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Mapped File way MappedByteBuffer 可以在处理大文件时，提升性能
	 * 
	 * @param filename
	 * @return
	 * @throws IOException
	 */
	public static byte[] toByteArray3(String filePath) throws IOException {

		FileChannel fc = null;
		RandomAccessFile rf = null;
		try {
			rf = new RandomAccessFile(filePath, "r");
			fc = rf.getChannel();
			MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0,
					fc.size()).load();
			//System.out.println(byteBuffer.isLoaded());
			byte[] result = new byte[(int) fc.size()];
			if (byteBuffer.remaining() > 0) {
				// System.out.println("remain");
				byteBuffer.get(result, 0, byteBuffer.remaining());
			}
			return result;
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				rf.close();
				fc.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 写出到流
	 * @param in
	 * @param out
	 * @param size
	 * @throws IOException
	 */
	public static void writeStream(InputStream in, OutputStream out, int size) throws IOException {
		byte[] temp = new byte[size];
		while (true) {
			int nRead = 0;
			nRead = in.read(temp);
			if (nRead <= 0)
				break;
			out.write(temp, 0, nRead);
		}
		in.close();
		out.flush();
		out.close();
	}
	public static File openOrCreateFile(String newFilePath)
	  {
	    if ((newFilePath == null) || ("".equals(newFilePath.trim()))) {
	      return null;
	    }
	    int index = newFilePath.lastIndexOf(File.separator);
	    String folderPath = newFilePath.substring(0, index);
	    File folder = new File(folderPath);
	    if (!folder.exists())
	      folder.mkdirs();
	    File file = new File(newFilePath);
	    try {
	      if (!file.exists())
	        file.createNewFile();
	    } catch (IOException ex) {
	      ex.printStackTrace();
	      return null;
	    }
	    return file;
	  }

	  public static boolean copyFile(String srcfile, String destfile)
	  {
	    File fromFile = openOrCreateFile(srcfile);
	    return copyFile(fromFile, destfile);
	  }

	  public static boolean copyFile(File srcfile, String destfile) {
	    File toFile = openOrCreateFile(destfile);
	    return copyFile(srcfile, toFile);
	  }

	  public static boolean copyFile(File fromFile, File toFile)
	  {
	    boolean result = true;

	    if ((!fromFile.exists()) || (!fromFile.isFile()) || (!fromFile.canRead())) {
	      return false;
	    }
	    if ((!toFile.exists()) || (!fromFile.isFile()) || (!fromFile.canRead())) {
	      return false;
	    }
	    try
	    {
	      FileInputStream fosfrom = new FileInputStream(fromFile);
	      FileOutputStream fosto = new FileOutputStream(toFile);
	      writeStream(fosfrom, fosto, 1024);
	    } catch (IOException e) {
	      result = false;
	    }
	    return result;
	  }

	  public static synchronized String generateRandomFileName(String fileName)
	  {
	    String formatDate = DATEFORMAT_TIME17BIT.format(new Date());

	    String random = getRandom(3);

	    int position = fileName.lastIndexOf(".");
	    String extension;
	    if (position == -1)
	      extension = DEFAULT_FILE_EXTENSION;
	    else {
	      extension = fileName.substring(position);
	    }

	    return formatDate + random + extension;
	  }

	  public static String getFileNameByPath(String strPath)
	  {
	    if ((strPath == null) || ("".equals(strPath.trim()))) {
	      return "";
	    }
	    int iIndex = strPath.lastIndexOf(PATH_SEPARATOR);
	    if (iIndex == -1) {
	      return "";
	    }
	    return strPath.substring(iIndex + 1);
	  }

	  /**
	   * 根据路径删除文件
	   * @param path
	   * @param excludeFolder
	   * @return
	   */
	  public static boolean deleteFileByPath(String path, String excludeFolder)
	  {
	    if ((path == null) || ("".equals(path.trim()))) {
	      return false;
	    }
	    File file = new File(path);
	    if (!file.exists()) {
	      return false;
	    }
	    if (!file.isFile()) {
	      return false;
	    }
	    file.delete();
	    deleteFolder(file.getParent(), excludeFolder);
	    return true;
	  }

	  /**
	   * 删除文件夹
	   * @param dirStr
	   * @param excludeFolder
	   */
	  public static void deleteFolder(String dirStr, String excludeFolder)
	  {
	    if (dirStr == null) {
	      return;
	    }

	    File dir = new File(dirStr);
	    if (!dir.exists()) {
	      return;
	    }

	    File[] files = dir.listFiles();

	    while (files.length == 0) {
	      if (dir.getName().equals(excludeFolder))
	      {
	        break;
	      }
	      File parentDir = dir.getParentFile();
	      dir.delete();
	      dir = parentDir;
	      files = dir.listFiles();
	    }
	  }

	  /**
	   * 根据路径获取文件名称
	   * @param strPath
	   * @param Separator
	   * @return
	   */
	  public static String getFileNameByPath(String strPath, String Separator)
	  {
	    if ((strPath == null) || ("".equals(strPath.trim()))) {
	      return "";
	    }
	    if ((Separator == null) || ("".equals(Separator))) {
	      Separator = PATH_SEPARATOR;
	    }

	    int iIndex = strPath.lastIndexOf(Separator);
	    if (iIndex == -1) {
	      return "";
	    }
	    return strPath.substring(iIndex + 1);
	  }

	  public static String getFileNmWithoutExt(String fileNm)
	  {
	    int num = fileNm.lastIndexOf(".");
	    if (num > 0) {
	      return fileNm.substring(0, num - 1);
	    }
	    return "";
	  }

	  /**
	   * 获取文件大小
	   * @param file
	   * @return
	   * @throws IOException
	   */
	  public static long getFileSize(File file)
	    throws IOException
	  {
	    long s = 0L;
	    if (file.exists()) {
	      FileInputStream fis = null;
	      fis = new FileInputStream(file);
	      s = fis.available();
	    } else {
	      file.createNewFile();
	      System.out.println("文件不存在");
	    }
	    return s;
	  }

	  public static long getDirectorySize(File file)
	    throws IOException
	  {
	    long size = 0L;
	    File[] flist = file.listFiles();
	    for (int i = 0; i < flist.length; i++) {
	      if (flist[i].isDirectory())
	        size += getFileSize(flist[i]);
	      else {
	        size += flist[i].length();
	      }
	    }
	    return size;
	  }

	  /**
	   * 格式化文件大小
	   * @param fileSize
	   * @return
	   */
	  public static String formetFileSize(long fileSize)
	  {
	    DecimalFormat df = new DecimalFormat("#.00");
	    String fileSizeString = "";
	    if (fileSize < 1024L)
	      fileSizeString = df.format(fileSize) + "B";
	    else if (fileSize < 1048576L)
	      fileSizeString = df.format(fileSize / 1024.0D) + "K";
	    else if (fileSize < 1073741824L)
	      fileSizeString = df.format(fileSize / 1048576.0D) + "M";
	    else {
	      fileSizeString = df.format(fileSize / 1073741824.0D) + "G";
	    }
	    return fileSizeString;
	  }

	  public long getlist(File f)
	  {
	    long size = 0L;
	    File[] flist = f.listFiles();
	    size = flist.length;
	    for (int i = 0; i < flist.length; i++) {
	      if (flist[i].isDirectory()) {
	        size += getlist(flist[i]);
	        size -= 1L;
	      }
	    }
	    return size;
	  }

	  public static String addPathSep(String strPath)
	  {
	    if ((strPath == null) || ("".equals(strPath.trim()))) {
	      return "";
	    }
	    if (strPath.endsWith(PATH_SEPARATOR)) {
	      return strPath;
	    }
	    return strPath + PATH_SEPARATOR;
	  }

	  private static final String getRandom(int pLength)
	  {
	    String random = "";
	    for (int i = 0; i < pLength; i++) {
	      int t = (int)(Math.random() * 10.0D);
	      random = random + String.valueOf(t);
	    }
	    return random;
	  }

	  public static synchronized void copy(File in, File out)
	    throws IOException
	  {
	    copy(new BufferedInputStream(new FileInputStream(in)), 
	      new BufferedOutputStream(new FileOutputStream(out)));
	  }

	  public static synchronized void copy(byte[] in, File out)
	    throws IOException
	  {
	    ByteArrayInputStream inStream = new ByteArrayInputStream(in);
	    OutputStream outStream = new BufferedOutputStream(new FileOutputStream(
	      out));
	    copy(inStream, outStream);
	  }

	  public static synchronized byte[] copyToByteArray(File in)
	    throws IOException
	  {
	    return copyToByteArray(new BufferedInputStream(new FileInputStream(in)));
	  }

	  public static synchronized void copy(InputStream in, OutputStream out)
	    throws IOException
	  {
	    try
	    {
	      byte[] buffer = new byte[4096];
	      int nrOfBytes = -1;
	      while ((nrOfBytes = in.read(buffer)) != -1) {
	        out.write(buffer, 0, nrOfBytes);
	      }
	      out.flush();
	    } finally {
	      try {
	        in.close();
	      } catch (IOException ex) {
	    	  throw new IOException("Could not close InputStream", ex);
	      }
	      try {
	        out.close();
	      } catch (IOException ex) {
	    	  throw new IOException("Could not close InputStream", ex);
	      }
	    }
	  }

	  public static synchronized void copy(byte[] in, OutputStream out)
	    throws IOException
	  {
	    try
	    {
	      out.write(in);
	    } finally {
	      try {
	        out.close();
	      } catch (IOException ex) {
	    	  throw new IOException("Could not close InputStream", ex);
	      }
	    }
	  }

	  public static synchronized byte[] copyToByteArray(InputStream in)
	    throws IOException
	  {
	    ByteArrayOutputStream out = new ByteArrayOutputStream();
	    copy(in, out);
	    return out.toByteArray();
	  }

	  public static synchronized void copy(Reader in, Writer out)
	    throws IOException
	  {
	    try
	    {
	      char[] buffer = new char[4096];
	      int nrOfBytes = -1;
	      while ((nrOfBytes = in.read(buffer)) != -1) {
	        out.write(buffer, 0, nrOfBytes);
	      }
	      out.flush();
	    } finally {
	      try {
	        in.close();
	      } catch (IOException ex) {
	    	  throw new IOException("Could not close Reader", ex);
	      }
	      try {
	        out.close();
	      } catch (IOException ex) {
	    	  throw new IOException("Could not close Writer", ex);
	      }
	    }
	  }

	  public static synchronized void copy(String in, Writer out)
	    throws IOException
	  {
	    try
	    {
	      out.write(in);
	    } finally {
	      try {
	        out.close();
	      } catch (IOException ex) {
	    	  throw new IOException("Could not close Writer", ex);
	      }
	    }
	  }

	  public static synchronized String copyToString(Reader in)
	    throws IOException
	  {
	    StringWriter out = new StringWriter();
	    copy(in, out);
	    return out.toString();
	  }

	  public static synchronized String copyToString(String filePath) throws IOException
	  {
	    BufferedReader is = new BufferedReader(new FileReader(filePath));
	    return copyToString(is);
	  }

	  public static synchronized String copyToString(String filePath, String uniCode) throws IOException
	  {
	    FileInputStream fis = new FileInputStream(new File(filePath));
	    BufferedReader buffReader = new BufferedReader(new InputStreamReader(
	      fis, uniCode));
	    StringBuffer strBuffer = new StringBuffer();
	    String tmpstr = "";
	    while ((tmpstr = buffReader.readLine()) != null) {
	      strBuffer.append(tmpstr);
	      strBuffer.append("\n");
	    }
	    buffReader.close();
	    fis.close();
	    return strBuffer.toString();
	  }

	  public static synchronized File assignFile(String directory, String fileName) throws FileException
	  {
	    File dir = new File(directory);
	    if (!dir.exists()) {
	      if (!dir.mkdirs())
	    	  new FileException("不能创建目录: " + directory);
	    }
	    else if (!dir.isDirectory()) {
	    	  new FileException(directory + "是一个目录");
	    }

	    File _file = new File(dir, fileName);
	    try {
	      if (!_file.exists()) {
	    	  _file.createNewFile();
	    	  throw new FileException("file [" + fileName + "] 没找到, 将创建一个新文件.");
	      }
	    } catch (IOException e) {
	      e.printStackTrace();
	    }
	    return _file;
	  }

	  public static synchronized File assignFile(File file) throws FileException
	  {
	    String path = file.getPath();
	    String dir = path.substring(0, path.lastIndexOf(File.separator));
	    String name = path.substring(path.lastIndexOf(File.separator) + 1, path
	      .length());
	    return assignFile(dir, name);
	  }

	  public static synchronized void lowerCaseFile(File file, boolean renameDirectory)
	    throws FileNotFoundException, IOException
	  {
	    if (file.isFile())
	    {
	      String lowerNameFilePath = file.getParent() + File.separator + 
	        file.getName().toLowerCase();
	      File lowerFile = new File(lowerNameFilePath);
	      file.renameTo(lowerFile);
	    } else if (file.isDirectory())
	    {
	      if (renameDirectory) {
	        String lowerNameDir = file.getParent() + File.separator + 
	          file.getName().toLowerCase();
	        File lowerDir = new File(lowerNameDir);
	        file.renameTo(lowerDir);
	      }
	    }
	  }

	  public static synchronized void lowerCaseFile(String nFile, boolean renameDirectory)
	    throws FileNotFoundException, IOException
	  {
	    File file = new File(nFile);
	    lowerCaseFile(file, renameDirectory);
	  }

	  public static synchronized void lowerCaseDirectory(File dir, boolean renameDirectory)
	    throws FileNotFoundException, IOException
	  {
	    if ((dir == null) || (!dir.isDirectory())) {
	      return;
	    }

	    File[] entries = dir.listFiles();
	    int sz = entries.length;
	    for (int i = 0; i < sz; i++) {
	      if (entries[i].isDirectory())
	        lowerCaseDirectory(entries[i], renameDirectory);
	      else {
	        lowerCaseFile(entries[i], renameDirectory);
	      }
	    }
	    lowerCaseFile(dir, renameDirectory);
	  }

	  public static synchronized boolean deleteDirectory(String directoryPath) {
	    try {
	      if (directoryPath == null) {
	        return false;
	      }
	      File file = new File(directoryPath);
	      if (file.exists()) {
	        return deleteDirectory(file);
	      }

	      return true; } catch (Exception e) {
	    }
	    return false;
	  }

	  public static synchronized boolean deleteDirectory(File file)
	  {
	      if ((file == null) || (!file.isDirectory())) {
	        return false;
	      }

	      if (!file.exists()) {
	        return true;
	      }

	      File[] entries = file.listFiles();
	      int sz = entries.length;
	      for (int i = 0; i < sz; i++) {
	        if (entries[i].isDirectory()) {
	          if (!deleteDirectory(entries[i]))
	            return false;
	        }
	        else {
	          entries[i].delete();
	        }
	      }

	      file.delete();
	      return true;
	  }

	  public static synchronized boolean deleteFile(String filePath)
	  {
	      File file = new File(filePath);
	      if (file.exists()) {
	        return file.delete();
	      }
	      return true;
	  }

	  public static synchronized boolean newFolder(String folderPath)
	  {
	      String filePath = folderPath;
	      filePath = filePath.toString();
	      File myFilePath = new File(filePath);
	      if (!myFilePath.exists()) {
	        return myFilePath.mkdirs();
	      }
	      return true;
	  }

	  public static synchronized void newFile(String filePathAndName, String fileContent) throws IOException
	  {
	      File myFilePath = new File(filePathAndName);
	      if (!myFilePath.exists()) {
	        myFilePath.createNewFile();
	      }
	      FileWriter resultFile = new FileWriter(myFilePath);
	      PrintWriter myFile = new PrintWriter(resultFile);
	      myFile.println(fileContent);
	      resultFile.close();
	  }

	  public static synchronized void newFile(String filePathAndName, String fileContent, String uniCode) throws IOException
	  {
	      File myFilePath = new File(filePathAndName);
	      if (!myFilePath.exists()) {
	        myFilePath.createNewFile();
	      }
	      FileOutputStream fos = new FileOutputStream(myFilePath);
	      OutputStreamWriter osw = new OutputStreamWriter(fos, uniCode);
	      osw.write(fileContent);
	      osw.close();
	      fos.close();
	   
	  }

	  public static synchronized boolean newFile(byte[] filebytes, String filename)
	  {
	    try
	    {
	      FileOutputStream fos = new FileOutputStream(filename);
	      fos.write(filebytes);
	      fos.flush();
	      fos.close();
	      return true;
	    } catch (Exception e) {
	      e.printStackTrace();
	    }return false;
	  }

	  public static synchronized boolean newFile(InputStream inputStream, String filename)
	  {
	    try
	    {
	      byte[] buffer = new byte[1024];
	      FileOutputStream fos = new FileOutputStream(filename);
	      int endIndex = 0;
	      while ((endIndex = inputStream.read(buffer)) != -1) {
	        fos.write(buffer, 0, endIndex);
	      }
	      fos.flush();
	      fos.close();
	      return true;
	    } catch (Exception e) {
	      e.printStackTrace();
	      return false;
	    } finally {
	      try {
	        inputStream.close();
	      } catch (IOException e) {
	        e.printStackTrace();
	      }
	    }
	  }

	  public static synchronized boolean updateFile(byte[] filebytes, String oldFileName, String newFileName, boolean deleted)
	  {
	    if (deleted) {
	      deleteFile(oldFileName);
	    }
	    newFile(filebytes, newFileName);
	    return true;
	  }

	  public static synchronized boolean updatefile(InputStream inputStream, String oldFileName, String newFileName, boolean deleted)
	  {
	    if (deleted)
	    {
	      deleteFile(oldFileName);
	    }

	    newFile(inputStream, newFileName);

	    return true;
	  }

	  public static synchronized void copyFolder(String oldPath, String newPath) throws IOException
	  {
	      new File(newPath).mkdirs();
	      File a = new File(oldPath);
	      String[] file = a.list();
	      File temp = null;
	      for (int i = 0; i < file.length; i++) {
	        if (oldPath.endsWith(File.separator))
	          temp = new File(oldPath + file[i]);
	        else {
	          temp = new File(oldPath + File.separator + file[i]);
	        }
	        if (temp.isFile()) {
	          FileInputStream input = new FileInputStream(temp);
	          FileOutputStream output = new FileOutputStream(newPath + 
	            "/" + temp.getName().toString());
	          byte[] b = new byte[5120];
	          int len;
	          while ((len = input.read(b)) != -1)
	          {
	            output.write(b, 0, len);
	          }
	          output.flush();
	          output.close();
	          input.close();
	        }
	        if (temp.isDirectory())
	          copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
	      }
	  }

	  public static synchronized void copyFolder(String oldPath, String newPath, String[] parse) throws IOException
	  {
	      new File(newPath).mkdirs();
	      File a = new File(oldPath);
	      String[] file = a.list();
	      File temp = null;
	      for (int i = 0; i < file.length; i++) {
	        if (oldPath.endsWith(File.separator))
	          temp = new File(oldPath + file[i]);
	        else {
	          temp = new File(oldPath + File.separator + file[i]);
	        }
	        if ((temp.isFile()) && (checkParse(temp.getName(), parse))) {
	          FileInputStream input = new FileInputStream(temp);
	          FileOutputStream output = new FileOutputStream(newPath + 
	            "/" + temp.getName().toString());
	          byte[] b = new byte[5120];
	          int len;
	          while ((len = input.read(b)) != -1)
	          {
	            output.write(b, 0, len);
	          }
	          output.flush();
	          output.close();
	          input.close();
	        }
	        if (temp.isDirectory())
	          copyFolder(oldPath + "/" + file[i], 
	            newPath + "/" + file[i], parse);
	      }
	    
	  }

	  private static boolean checkParse(String fileName, String[] parse)
	  {
	    if ((parse != null) && (parse.length > 0)) {
	      for (String p : parse) {
	        if (fileName.toLowerCase().indexOf(p.toLowerCase()) > -1) {
	          return false;
	        }
	      }
	    }
	    return true;
	  }

	  public static synchronized void moveFile(String oldPath, String newPath)
	  {
	    copyFile(oldPath, newPath);
	    deleteDirectory(new File(oldPath));
	  }

	  public static synchronized void moveFolder(String oldPath, String newPath) throws IOException
	  {
	    copyFolder(oldPath, newPath);
	    deleteDirectory(new File(oldPath));
	  }

	  public static synchronized String createFileNameByDateTime()
	  {
	    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
	      "yyyyMMddHHmmssSSS");

	    return simpleDateFormat.format(new Date());
	  }

	  public static String readFile(File file)
	  {
	    StringBuffer output = new StringBuffer("");
	    if (file.exists()) {
	      if (file.isFile()) {
	        try {
	          BufferedReader input = new BufferedReader(new FileReader(
	            file));
	          StringBuffer buffer = new StringBuffer();
	          String text;
	          while ((text = input.readLine()) != null)
	          {
	            buffer.append(text + "\n");
	          }output.append(buffer.toString());
	        } catch (IOException ioException) {
	          System.err.println("File Error!");
	        }
	      } else if (file.isDirectory()) {
	        String[] dir = file.list();
	        output.append("Directory contents:\n");
	        for (int i = 0; i < dir.length; i++)
	          output.append(dir[i] + "\n");
	      }
	    }
	    else {
	      System.err.println("Does not exist!");
	    }
	    return output.toString();
	  }

	  public static void readFileByBytes(String fileName)
	  {
	    File file = new File(fileName);
	    InputStream in = null;
	    try {
	      System.out.println("以字节为单位读取文件内容，一次读一个字节：");

	      in = new FileInputStream(file);
	      int tempbyte;
	      while ((tempbyte = in.read()) != -1)
	      {
	        System.out.write(tempbyte);
	      }
	      in.close();
	    } catch (IOException e) {
	      e.printStackTrace();
	      return;
	    }
	    try {
	      System.out.println("以字节为单位读取文件内容，一次读多个字节：");

	      byte[] tempbytes = new byte[100];
	      int byteread = 0;
	      in = new FileInputStream(fileName);
	      showAvailableBytes(in);

	      while ((byteread = in.read(tempbytes)) != -1)
	        System.out.write(tempbytes, 0, byteread);
	    }
	    catch (Exception e1) {
	      e1.printStackTrace();

	      if (in != null)
	        try {
	          in.close();
	        }
	        catch (IOException localIOException1)
	        {
	        }
	    }
	    finally
	    {
	      if (in != null)
	        try {
	          in.close();
	        }
	        catch (IOException localIOException2)
	        {
	        }
	    }
	  }

	  public static void readFileByChars(String fileName)
	  {
	    File file = new File(fileName);
	    Reader reader = null;
	    try {
	      System.out.println("以字符为单位读取文件内容，一次读一个字节：");

	      reader = new InputStreamReader(new FileInputStream(file));
	      int tempchar;
	      while ((tempchar = reader.read()) != -1)
	      {
	        if ((char)tempchar != 'r') {
	          System.out.print((char)tempchar);
	        }
	      }
	      reader.close();
	    } catch (Exception e) {
	      e.printStackTrace();
	    }
	    try {
	      System.out.println("以字符为单位读取文件内容，一次读多个字节：");

	      char[] tempchars = new char[30];
	      int charread = 0;
	      reader = new InputStreamReader(new FileInputStream(fileName));

	      while ((charread = reader.read(tempchars)) != -1)
	      {
	        if ((charread == tempchars.length) && 
	          (tempchars[(tempchars.length - 1)] != 'r'))
	          System.out.print(tempchars);
	        else
	          for (int i = 0; i < charread; i++)
	            if (tempchars[i] != 'r')
	            {
	              System.out.print(tempchars[i]);
	            }
	      }
	    }
	    catch (Exception e1)
	    {
	      e1.printStackTrace();

	      if (reader != null)
	        try {
	          reader.close();
	        }
	        catch (IOException localIOException)
	        {
	        }
	    }
	    finally
	    {
	      if (reader != null)
	        try {
	          reader.close();
	        }
	        catch (IOException localIOException1)
	        {
	        }
	    }
	  }

	  public static void readFileByLines(String fileName)
	  {
	    File file = new File(fileName);
	    BufferedReader reader = null;
	    try {
	      System.out.println("以行为单位读取文件内容，一次读一整行：");
	      reader = new BufferedReader(new FileReader(file));
	      String tempString = null;
	      int line = 1;

	      while ((tempString = reader.readLine()) != null)
	      {
	        System.out.println("line " + line + ": " + tempString);
	        line++;
	      }
	      reader.close();
	    } catch (IOException e) {
	      e.printStackTrace();

	      if (reader != null)
	        try {
	          reader.close();
	        }
	        catch (IOException localIOException1)
	        {
	        }
	    }
	    finally
	    {
	      if (reader != null)
	        try {
	          reader.close();
	        }
	        catch (IOException localIOException2)
	        {
	        }
	    }
	  }

	  public static void readFileByRandomAccess(String fileName)
	  {
	    RandomAccessFile randomFile = null;
	    try {
	      System.out.println("随机读取一段文件内容：");

	      randomFile = new RandomAccessFile(fileName, "r");

	      long fileLength = randomFile.length();

	      int beginIndex = fileLength > 4L ? 4 : 0;

	      randomFile.seek(beginIndex);
	      byte[] bytes = new byte[10];
	      int byteread = 0;

	      while ((byteread = randomFile.read(bytes)) != -1)
	        System.out.write(bytes, 0, byteread);
	    }
	    catch (IOException e) {
	      e.printStackTrace();

	      if (randomFile != null)
	        try {
	          randomFile.close();
	        }
	        catch (IOException localIOException1)
	        {
	        }
	    }
	    finally
	    {
	      if (randomFile != null)
	        try {
	          randomFile.close();
	        }
	        catch (IOException localIOException2)
	        {
	        }
	    }
	  }

	  private static void showAvailableBytes(InputStream in)
	  {
	    try
	    {
	      System.out.println("当前字节输入流中的字节数为:" + in.available());
	    } catch (IOException e) {
	      e.printStackTrace();
	    }
	  }

	  public static void appendMethodA(String fileName, String content)
	  {
	    try
	    {
	      RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");

	      long fileLength = randomFile.length();

	      randomFile.seek(fileLength);
	      randomFile.writeBytes(content);
	      randomFile.close();
	    } catch (IOException e) {
	      e.printStackTrace();
	    }
	  }

	  public static void appendMethodB(String fileName, String content)
	  {
	    try
	    {
	      FileWriter writer = new FileWriter(fileName, true);
	      writer.write(content);
	      writer.close();
	    } catch (IOException e) {
	      e.printStackTrace();
	    }
	  }

	  public static void writeByFileWriter(String fileName, String content) {
	    try {
	      FileWriter fw = new FileWriter(fileName);
	      fw.write(content, 0, content.length());
	      fw.flush();
	      fw.close();
	    } catch (IOException e) {
	      e.printStackTrace();
	    }
	  }

	  public static void writeByStream(String fileName, String content, String encode)
	  {
	    try {
	      OutputStreamWriter osw = new OutputStreamWriter(
	        new FileOutputStream(fileName), encode);
	      osw.write(content, 0, content.length());
	      osw.flush();
	      osw.close();
	    } catch (FileNotFoundException e) {
	      e.printStackTrace();
	    } catch (IOException e) {
	      e.printStackTrace();
	    }
	  }

	  public static void writeByPrint(String fileName, String content, String encode)
	  {
	    try {
	      PrintWriter pw = new PrintWriter(new OutputStreamWriter(
	        new FileOutputStream(fileName), encode), true);
	      pw.println(content);
	      pw.close();
	    } catch (FileNotFoundException e) {
	      e.printStackTrace();
	    } catch (UnsupportedEncodingException e) {
	      e.printStackTrace();
	    }
	  }

	  public static boolean writeString2File(String res, String filePath)
	  {
	    boolean flag = true;
	    BufferedReader bufferedReader = null;
	    BufferedWriter bufferedWriter = null;
	    try {
	      File distFile = new File(filePath);
	      if (!distFile.getParentFile().exists())
	        distFile.getParentFile().mkdirs();
	      bufferedReader = new BufferedReader(new StringReader(res));
	      bufferedWriter = new BufferedWriter(new FileWriter(distFile));
	      char[] buf = new char[1024];
	      int len;
	      while ((len = bufferedReader.read(buf)) != -1)
	      {
	        bufferedWriter.write(buf, 0, len);
	      }
	      bufferedWriter.flush();
	      bufferedReader.close();
	      bufferedWriter.close();
	    } catch (IOException e) {
	      e.printStackTrace();
	      flag = false;
	      boolean bool1 = flag; return bool1;
	    } finally {
	      if (bufferedReader != null) {
	        try {
	          bufferedReader.close();
	        } catch (IOException e) {
	          e.printStackTrace();
	        }
	      }
	    }
	    return flag;
	  }

	  public static String readStringFromFile(File file, String encoding)
	  {
	    InputStreamReader reader = null;
	    StringWriter writer = new StringWriter();
	    try {
	      if ((encoding == null) || ("".equals(encoding.trim())))
	        reader = new InputStreamReader(new FileInputStream(file), 
	          encoding);
	      else {
	        reader = new InputStreamReader(new FileInputStream(file));
	      }
	      char[] buffer = new char[1024];
	      int n = 0;
	      while (-1 != (n = reader.read(buffer)))
	        writer.write(buffer, 0, n);
	    }
	    catch (Exception e) {
	      e.printStackTrace();
	      return null;
	    } finally {
	      if (reader != null)
	        try {
	          reader.close();
	        } catch (IOException e) {
	          e.printStackTrace();
	        }
	    }
	    if (writer != null) {
	      return writer.toString();
	    }
	    return null;
	  }

	  public static void inputStreamtoFile(InputStream ins, File file)
	  {
	    try
	    {
	      OutputStream os = new FileOutputStream(file);
	      int bytesRead = 0;
	      byte[] buffer = new byte[8192];
	      while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
	        os.write(buffer, 0, bytesRead);
	      }
	      os.close();
	      ins.close();
	    } catch (Exception e) {
	      e.printStackTrace();
	    }
	  }

}